package unti

import (
	"answer5/adb"
	log2 "answer5/log"
	"encoding/json"
	"fmt"
	"golang.org/x/net/websocket"
	"log"
	"strings"
	"time"
)

var(
	webs         *websocket.Conn
	receiveRaw   string
	receiveData  = &ReceiveData{}
	err error
)

func StartWs(ws *websocket.Conn,start func(string),stop func()){
	webs = ws
	defer webs.Close()
	for {
		if err = websocket.Message.Receive(ws, &receiveRaw); err != nil {
			SendErr(err, "接收数据异常")
			stop()
			break
		}

		if err = json.Unmarshal([]byte(receiveRaw), receiveData); err != nil {
			SendErr(err, "json->struct 异常")
			continue
		}

		switch receiveData.Act {
		case "start":
			start(receiveData.App)
		case "stop":
			stop()
		case "search":
			words := strings.Split(receiveData.Data, " ")
			for _, word := range words {
				go baike(&receiveData.Round, &word)
			}
		case "magiCookie":
			SetMagiCookie(receiveData.Data)
		case "baiduToken":
			baiduToken = receiveData.Data
		case "createBaiduToken":
			getBaiduToken()
		case "xiaoYuan":
			XiaoYuan()
		case "dumpQuestion":
			app := receiveData.Data
			adb.UiAutomatorDump()
			if app == "huYa"{
				//huYa.DumpQuestion()
				start("huYaDump")
			}

		case "test":
			go log2.LogPrint(receiveData.Data)
			if receiveData.Data == "kuaiShou"{
				a:="kuaiShouTest"
				start(a)
			}else if receiveData.Data == "adb"{
				a:="adb"
				start(a)
			}else if (receiveData.Data == "start-uiautomator"){
				adb.StartUiautomator()
			}else if (receiveData.Data == "get-hierarchy"){
				t:=time.Now()
				fmt.Println(string(*adb.GetHierarchy()))
				st:=time.Since(t)
				fmt.Println(st)
			}
		default:
			SendErr(err, "无此命令"+receiveData.Act)
		}
		go log2.LogPrint("act " + receiveData.Act + ": " + receiveData.Data)
	}
}

func SendNewQuestion(question *Question){
	if webs != nil {
		data := SendDataNewQuestion{}
		data.Success = true
		data.Act = "NewQuestion"
		data.Data = question
		raw, err := json.Marshal(data)
		if err != nil {
			SendErr(err, "SendNewQuestion 异常")
			return
		}
		if err = websocket.Message.Send(webs, string(raw)); err != nil {
			log.Println(err)
			go log2.ErrorPrint(err.Error())
		}
	}
}
func SendNewAnswer(question *Question){
	if webs != nil {
		data := SendDataNewQuestion{}
		data.Success = true
		data.Act = "NewAnswer"
		data.Data = question
		raw, err := json.Marshal(data)
		if err != nil {
			SendErr(err, "SendNewAnswer 异常")
			return
		}
		if err = websocket.Message.Send(webs, string(raw)); err != nil {
			log.Println(err)
			go log2.ErrorPrint(err.Error())
		}
	}
}
func SendRandomOption(options *[]*[]*[]string, round *int32) {
	if webs != nil {
		data := SendDataRandomOption{
			Data: options,
		}
		data.Success = true
		data.Act = "Random"
		data.Round = round
		raw, _ := json.Marshal(data)
		if err = websocket.Message.Send(webs, string(raw)); err != nil {
			log.Println(err)
			go log2.ErrorPrint(err.Error())
		}
	}
}
func SendNewContent(contents *[]string,matches *map[string]*OptionMatch,round *int32){
	if webs != nil {
		data := &SendDataContent{}
		data.Success = true
		data.Act = "Content"
		data.Data = &DataContent{Content: contents, Matches: matches, Round: round}
		raw, _ := json.Marshal(*data)
		if err = websocket.Message.Send(webs, string(raw)); err != nil {
			log.Println(err)
			go log2.ErrorPrint(err.Error())
		}
	}
}
func SendSearchContent(contents *[]string,matches *map[string]*OptionMatch,round *int32){
	if webs != nil {
		data := &SendDataContent{}
		data.Success = true
		data.Act = "SearchContent"
		data.Data = &DataContent{Content: contents, Matches: matches, Round: round}
		raw, _ := json.Marshal(*data)
		if err = websocket.Message.Send(webs, string(raw)); err != nil {
			log.Println(err)
			go log2.ErrorPrint(err.Error())
		}
	}
}
func SendWordDataTitle(words *map[string]bool,round *int32){
	SendWordData(words,"WordTitle",round)
}
func SendWordDataOptions(words *map[string]bool,round *int32){
	SendWordData(words,"WordOptions",round)
}
func SendWordData(words *map[string]bool,t string,round *int32){
	if webs != nil {
		data := &SendDataWord{}
		data.Success = true
		data.Act = t
		data.Data = words
		data.Round = round
		raw, _ := json.Marshal(*data)
		if err = websocket.Message.Send(webs, string(raw)); err != nil {
			log.Println(err)
			go log2.ErrorPrint(err.Error())
		}
	}
}
func SendErr(err error, message string) {
	if webs != nil {
		sendData := &SendData{}
		sendData.Success = false
		sendData.Message = message
		raw, _ := json.Marshal(sendData)
		jsonStr := string(raw)
		if e := websocket.Message.Send(webs, jsonStr); e != nil {
			log.Println(e)
			go log2.ErrorPrint(err.Error())
		}
	}
	log.Println(message + ": " + err.Error())
	go log2.ErrorPrint(message + ": " + err.Error())
}
func SendBaiduToken(token string){
	if webs != nil{
		d := &SendData{}
		d.Success = true
		d.Act = "NewBaiduToken"
		d.Data = token
		raw, _ := json.Marshal(*d)
		if err = websocket.Message.Send(webs, string(raw)); err != nil {
			log.Println(err)
			go log2.ErrorPrint(err.Error())
		}
	}

}

type SendData struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Act     string `json:"act"`
	Data    string `json:"data"`
	Round *int32 `json:"round"`
}
type SendDataNewQuestion struct {
	SendData
	Data *Question `json:"data"`
}
type SendDataRandomOption struct {
	SendData
	Data  *[]*[]*[]string `json:"data"`
}
type SendDataNewOption struct {
	SendData
	Data []string `json:"data"`
}
type SendDataContent struct {
	SendData
	Data *DataContent `json:"data"`
}
type SendDataWord struct{
	SendData
	Data *map[string]bool `json:"data"`
}
type DataContent struct {
	Content    *[]string                  `json:"content"`
	Matches    *(map[string]*OptionMatch) `json:"matches"`
	Round      *int32                     `json:"round"`
	TitleWords *map[string]bool           `json:"titleWords"`
}
type OptionMatch struct {
	PMatch int `json:"pMatch"`
	FMatch int `json:"fMatch"`
}
type ReceiveData struct {
	Act   string `json:"act"`
	App   string `json:"app"`
	Round int32  `json:"round"`
	Data  string `json:"data"`
}